﻿#include "broadcastDecode.h"
#include <QtCore/QDebug>
#include <QtCore/QDateTime>

BroadcastDecode::BroadcastDecode() :
	_currentCNTR(0) {
	_sensorCache.clear();
}

BroadcastDecode::~BroadcastDecode() {
	
}

//提交数据到显示缓存队列
void BroadcastDecode::pushToList() {
	if (_sensorCache.count() > 0) {
		//互斥锁
		App::curvesMutex.lock();
		App::sensorCurveCache.append(_sensorCache);
		App::curvesMutex.unlock();
	}
}

void BroadcastDecode::sensorPacketDecode(uint8_t *src, uint16_t length) {
	uint8_t ptr = 6;
	uint8_t packetNum = src[ptr++];
	for (uint8_t j = 0; j < packetNum; j++) {
		uint8_t baseCurves = src[ptr++];
		uint8_t cellLength = pow(2, (src[ptr] & 0x03));
		uint8_t structLength = (src[ptr] & 0x3C) >> 2;
		uint8_t properties = (src[ptr++] & 0xC0) >> 6;
		for (int i = 0; i < structLength; i++, ptr += cellLength) {
			double value;
			switch (cellLength) {
				case sizeof(int16_t) :
					value = ByteConverter::ByteTo16Bit<int16_t>(src, ptr);
					break;
				case sizeof(float) :
					value = ByteConverter::ByteTo32Bit<float>(src, ptr);
					break;
				case sizeof(double) :
					value = ByteConverter::ByteTo64Bit<double>(src, ptr);
					break;
			}
			//添加该数据到缓存
			SensorCache cache = SensorCache(baseCurves + i, cellLength, properties, _currentCNTR, value);
			_sensorCache.append(cache);
		}
	}
}

//日志数据解析
void BroadcastDecode::logPacketDecode(uint8_t *src, uint16_t length) {
	uint8_t ptr = 6;
	uint8_t logLength = length - (6 + 2);
	QByteArray u8Data;
	for (uint8_t i = 0; i < logLength; i++) {
		u8Data.append(src[ptr++]);
	}
	log = QString(u8Data);
	qDebug() << QDateTime::currentDateTime().toString("[yyyy.MM.dd hh:mm:ss.zzz]log: %1").arg(log);
	emit stringDecode(log);
}

//数据解析
void BroadcastDecode::decode(uint8_t *src, uint16_t length) {
	uint8_t frameType = src[1];
	//当前的CNTR
	_currentCNTR = ByteConverter::ByteTo16Bit<uint16_t>(src, 3);
	//根据帧类型选择数据包的解析方式
	switch (frameType) {
	case FRAME_TYPE_SENSOR:
		sensorPacketDecode(src, length);
		break;
	case FRAME_TYPE_LOG:
		logPacketDecode(src, length);
		break;
	}
	//追加到曲线待填装缓存
	pushToList();
	//清除缓存
	_sensorCache.clear();
}